<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2017-11-20
 * Time: 10:25
 *
 */
namespace app\store\controller;


use app\store\model\OrderDetails;
use app\store\model\StoreGoodsLog;
use controller\BasicAdmin;
use think\Controller;
use think\Db;

class Cash extends BasicAdmin
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'Order';

    public function index()
    {
        $this->title = '订单列表';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];

        $join = [
            ['ys_user b', 'b.uid=a.uid', 'LEFT'],
        ];
        $db = Db::name($this->table)->alias('a')->join($join)->where('a.store_id', $store_id)->where('a.order_type', 0)->field('a.*,b.realname,b.mobile')->order('a.id desc');

        foreach (['order_sn'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $this->assign('date', $start . " - " . $end);

            $start = $start . "  00:00:00";
            $end = $end . " 23:59:59";
            $start = strtotime($start);
            $end = strtotime($end);

            $db->whereBetween('a.addtime', ["{$start}", "{$end}"]);

        } else {
            $this->assign('date', '');
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        return parent::_list($db);
    }


    /**
     * 订单详情
     * @Author   lingyun
     * @DateTime 2017-11-22T08:41:43+0800
     * @return   [type]                   [description]
     */
    public function detail()
    {
        $id = input('id');
        $join = [
            ['ys_goods b', 'a.goods_id=b.id', 'LEFT'],
            ['ys_order c', 'a.id=c.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.spec_id=d.id', 'LEFT']
        ];
        //下单人信息以及订单信息
        $info = Db::name('order')->alias('c')->join('ys_user d', 'd.uid=c.uid', 'LEFT')->field('d.realname,d.mobile,d.uid,d.email,c.*')->where('c.id', $id)->find();

        //订单操作记录
        $action = Db::name('order_action')->alias('f')->join('ys_system_user e', 'f.action_user=e.id', 'LEFT')->field('f.*,e.username')->where('f.order_id', $id)->order('f.id asc')->select();        //订单action

        //订单商品详情
        $db = Db::name('order_details')->alias('a')->join($join)->where('a.order_id', $id)->field('a.*,a.goods_num anum,a.id aid,a.tuihuo_sign atuihuo,a.final_amount amount,b.*,c.*,d.*')->order('a.id desc');
        $this->assign('info', $info);
        $this->assign('action', $action);
        return parent::_list($db);
    }

    /**
     * 收银台
     * @return mixed
     * @throws \Exception
     * @throws \think\Exception
     */
    public function cashier()
    {
        $user = session('user');

        if (request()->ispost()) {
            $post = input('post.');

            $post['nums'] = explode(',', $post['nums']);
            $post['goods'] = explode(',', $post['goods']);
            $post['price'] = explode(',', $post['prices']);
            $post['cat'] = explode(',', $post['cats']);

            $coupon_id = 0;//不使用优惠券

            $rate = 1;//默认折扣是1
            $total = $post['total'];//默认是原价
            if ($post['member']) {
                $member = db('user')->where('pay_code', $post['member'])->find();
                if (!$member)
                    $member = db('user')->where('mobile', $post['member'])->find();

                if ($member) {//定位到会员
                    if ($post['ycard']) {//使用优惠券
                        $ycard = db('view_user_ycard')->where('id', $post['ycard'])->find();//优惠券
                        $ymoney = 0;//符合优惠条件的金额
                        if ($ycard['cat_id'] === 0)//通用
                            $ymoney = $post['total'];
                        else//指定品类
                            foreach ($post['cat'] as $k => $v) {
                                if ($v == $ycard['cat_id'])
                                    $ymoney += $post['price'][$k] * $post['nums'][$k];
                            }
                        if ($ymoney < $ycard['morethan'])
                            return json(['code' => 0, 'msg' => '订单金额不足，无法使用该优惠券！']);
                        else{//使用优惠券
                            $coupon_id = $post['ycard'];
                            //计算优惠比例，优惠后价格/优惠前价格
                            $rate = ($ymoney-$ycard['reduce'])/$ymoney;
                            //计算优惠后的总价
                            $total = $post['total'] - $ycard['reduce'];
                            //更新优惠券为已使用
                            db('user_ycard')->update(['id'=>$post['ycard'], 'is_used'=>1]);
                        }
                    }
                    $uid = $member['uid'];
                    if ($post['method'] == 3 && $total > $member['user_money'])
                        return json(['code' => 0, 'msg' => '会员余额不足！']);
                } else
                    return json(['code' => 0, 'msg' => '会员卡号有误！']);

            } else
                $uid = 0;

            $num = array_sum($post['nums']);

            $sn = 'L' . build_order_no();
            //积分规则
            $sys_point = db('sys_point')->where('id',2)->find();
            $point_rate = $sys_point['point']/10;
            $sys_point2 = db('sys_point')->where('id',6)->find();
            $point_rate2 = $sys_point2['point']/10;

            //订单
            $point = ceil($total * $point_rate);
            $order = db('order')->insertGetid([
                'uid' => $uid,
                'coupon_id' => $coupon_id,
                'order_type' => 0,
                'order_sn' => $sn,
                'store_id' => $user['store_id'],
                'order_status' => 7,
                'pay_status' => 1,
                'pay_type' => $post['method'],
                'goods_price' => $post['total'],
                'final_amount' => $total,
                'receive_amount' => $post['receive'],
                'addtime' => time(),
                'pay_time' => time(),
                'goods_num' => $num,
                'score' => $point
            ]);

            $point_r = 1;//积分操作状态
            $user_money_r = 1;

            if ($uid > 0) {

                //扣余额
                if ($post['method'] == 3 && $total < $member['user_money']) {
                    $user_money = db('user')->where('uid', $uid)->setDec('user_money', $total);
                    $money_log = db('user_wallet_log')->insert([
                        'uid' => $uid,
                        'admin_id' => $user['id'],
                        'store_id' => $user['store_id'],
                        'order_id' => $order,
                        'pay_time' => time(),
                        'pay_status' => 1,
                        'amount' => -$total,
                        'cur_amount' => $member['user_money'] - $total,
                        'chargetype' => 1,
                        'addtime' => time()
                    ]);
                    if ($user_money === false || $money_log === false)
                        $user_money_r = 0;
                }


                $pay_points = db('user')->where('uid', $uid)->setInc('pay_points', $point);//权益积分
                $level_point = db('user')->where('uid', $uid)->setInc('level_point', $point);//等级积分

                //积分日志
                $point_log = db('user_point_log')->insert([
                    'uid' => $uid,
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'order_id' => $order,
                    'uidtype' => 1,
                    'type' => 1,
                    'point' => $point,
                    'curpoint' => $member['pay_points'] + $point,
                    'addtime' => time(),
                    'tuijianrenuid' => $member['pid']
                ]);

                $p = 1;
                if ($member['pid'] > 0) {
                    $point2 = $point * $point_rate2 / $point_rate;
                    //推荐人
                    $pm = db('user')->where('uid', $member['pid'])->find();
                    //积分日志
                    $point_log2 = db('user_point_log')->insert([
                        'uid' => $member['pid'],
                        'admin_id' => session('user')['id'],
                        'store_id' => session('user')['store_id'],
                        'order_id' => $order,
                        'uidtype' => 3,
                        'type' => 1,
                        'point' => $point2,
                        'curpoint' => $pm['pay_points'] + $point2,
                        'addtime' => time(),
                    ]);
                    $pay_points_p = db('user')->where('uid', $member['pid'])->setInc('pay_points', $point2);//权益积分
                    $level_point_p = db('user')->where('uid', $member['pid'])->setInc('level_point', $point2);//等级积分

                    if ($point_log2 === false || $pay_points_p === false || $level_point_p === false)
                        $p = 0;
                }

                if ($pay_points === false || $level_point === false || $point_log === false || $p === 0)
                    $point_r = 0;//积分失败
            }


            foreach ($post['nums'] as $k => $v) {
                $goods_stock = db('store_goods_stock')->find($post['goods'][$k]);
                $goods = db('goods')->find($goods_stock['goods_id']);

                $details[] = [
                    'uid' => $uid,
                    'order_id' => $order,
                    'spec_id' => $goods_stock['goods_spec_id'],
                    'spec_detail' => $goods_stock['spec_title'],
                    'goods_id' => $goods_stock['goods_id'],
                    'goods_num' => $v,
                    'spec_price' => $post['price'][$k] * $rate,
                    'final_amount' => $post['price'][$k] * $v * $rate,
                    'status' => 7,
                    'storeid' => $user['store_id'],
                    'is_online' => 0,
                    'addtime' => time()
                ];

                db('store_goods_stock')->where('id', $post['goods'][$k])->setDec('stock', $v);
                $cur_stock = db('store_goods_stock')->where('id', $post['goods'][$k])->find()['stock'];

                $log[] = [
                    'goods_id' => $goods_stock['goods_id'],
                    'goods_spec_id' => $goods_stock['goods_spec_id'],
                    'title' => $goods_stock['spec_title'],
                    'order_id' => $order,
                    'store_id' => $user['store_id'],
                    'chuku_num' => $v,
                    'remark' => $sn,
                    'cur_stock' => $cur_stock,
                    'addtime' => time()
                ];

                $order_list[] = [
                    'name' => $goods['name'] . ' ' . $goods_stock['spec_title'],
                    'num' => $v,
                    'price' => $post['price'][$k] * $rate,
                    'amount' => $post['price'][$k] * $v * $rate,
                ];
            }
            //出库记录
            $store_goods_log = new StoreGoodsLog();
            $orser_details = $store_goods_log->saveAll($log);

            //订单详情
            $order_details = new OrderDetails();
            $goods_log = $order_details->saveall($details);

            //订单动作
            $order_action = db('order_action')->insert([
                'uid' => $uid,
                'order_id' => $order,
                'action_user' => $user['id'],
                'storeid' => $user['store_id'],
                'status_desc' => '收银台交易完成',
                'addtime' => time(),
            ]);

            //小票内容
            $content = '';

            $content .= '<tr><td colspan="4" style="font-size: large;text-align: center">云上芭蕾</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号 ' . $sn . '</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员 ' . $user['id'] . '</td></tr><tr><td colspan="4" style="text-align: center">———————————————</td></tr><tr><td style="width: 25mm;">商品</td><td>数量</td><td>单价</td><td>小计</td></tr>';

            foreach ($order_list as $k => $v) {
                $content .= '<tr style="font-size: smaller;"><td colspan="4" style="text-align: left">' . $v['name'] . '</td></tr>';
                $content .= '<tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $v['num'] . '</td><td>' . floatval($v['price']) . '</td><td>' . $v['amount'] . '</td></tr>';
            }
            $content .= '<tr><td colspan="4" style="text-align: center">———————————————</td></tr>';

            switch ($post['method']) {
                case 1:
                    $method = '支付宝';
                    break;
                case 2:
                    $method = '微信';
                    break;
                case 3:
                    $method = '余额';
                    break;
                case 4:
                    $method = '现金';
                    break;
                case 5:
                    $method = '银行卡';
                    break;
            }
            $content .= '<tr><td colspan="4" style="text-align: center;font-size: smaller">总数量：' . $num . ' ' . $method . '：￥' . $total . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: center">' . '欢迎您再次光临' . '</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: center">' . date('Y-m-d H:i:s') . '</td></tr>';

            $receipt = db('order')->update(['id' => $order, 'receipt' => $content]);

            if ($goods_log !== false && $orser_details !== false && $order_action !== false && $order && $receipt !== false && $point_r === 1 && $user_money_r === 1)
                return json(['code' => 1, 'msg' => '结账成功！', 'data' => $content]);

        } else {
            $store = db('store')->find($user['store_id']);

            $join = [
                ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
                ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
            ];

            $goods = db('store_goods_stock')->alias('a')->join($join)->where('store_id', $user['store_id'])->field('a.*,g.name,g.is_spec,g.market_price,g.good_number,s.title')->select();

            foreach ($goods as $k => &$v) {
                if ($v['is_spec'] == 1)
                    $v['price'] = db('goods_spec_detail')->where('id', $v['goods_spec_id'])->find()['price'];
                else
                    $v['price'] = db('goods_spec_detail')->where('goods_id', $v['goods_id'])->where('specs', 0)->find()['price'];
            }

            $this->assign('store', $store);
            $this->assign('user', $user);
            $this->assign('goods', $goods);
            $this->assign('title', '收银台');

            return view();
        }
    }

    /**
     * 获取会员信息
     * @return mixed
     */
    public function member()
    {
        $store_id = session('user')['store_id'];
        $post = input();
        $member = db('user')->where('pay_code', $post['no'])->find();
        if (!$member)
            $member = db('user')->where('mobile', $post['no'])->find();
        $ycard = db('view_user_ycard')->where('uid', $member['uid'])->where('store_id', $store_id)->where('use_start_time', '<', time())->where('use_end_time', '>', time())->where('is_used', 0)->select();
        if ($member)
            return json([
                'name' => $member['realname'],
                'balance' => $member['user_money'],
                'ycard' => $ycard
            ]);
        else
            return json([
                'name' => '未找到该会员信息！',
                'balance' => '0.00',
                'ycard' => ''
            ]);
    }

    /**
     * 退货
     * @return array|string
     */
    public function cancel()
    {
        $id = input('id');
        $user = session('user');
        if (request()->ispost()) {
            $post = input('post.');
            $order_detail = db('order_details')->find($id);

            if ($order_detail['goods_num'] > $post['tuihuo_num'])
                $tuihuo_sign = 2;//部分退货
            elseif ($order_detail['goods_num'] < $post['tuihuo_num'])
                $this->error('超过购买数量！');
            else
                $tuihuo_sign = 1;//全部退货

            if ($order_detail['discount_signal_price'])
                $tuihuo_signal_price = $order_detail['discount_signal_price'];
            else
                $tuihuo_signal_price = $order_detail['spec_price'];

            $cancel_amount = $tuihuo_signal_price * $post['tuihuo_num'];

            $order_details = db('order_details')->update([
                'id' => $id,
                'tuihuo_num' => $post['tuihuo_num'],
                'th_deal_remark' => $post['th_deal_remark'],
                'tuihuo_sign' => $tuihuo_sign,
                'tuihuo_amount' => $cancel_amount,
                'tuihuo_time' => time(),
                'th_deal_admin' => $user['id']
            ]);

            //订单动作
            $order_action = db('order_action')->insert([
                'uid' => $order_detail['uid'],
                'order_id' => $order_detail['order_id'],
                'action_user' => $user['id'],
                'storeid' => $user['store_id'],
                'status_desc' => '处理退货',
                'addtime' => time(),
            ]);

            //报损
            $stock = db('store_goods_stock')->where(['goods_id' => $order_detail['goods_id'], 'goods_spec_id' => $order_detail['spec_id'], 'store_id' => $user['store_id']])->find();
            $log = db('store_goods_log')->insert(['store_id' => $user['store_id'], 'goods_id' => $order_detail['goods_id'], 'sunhao_num' => $post['tuihuo_num'], 'tuihuo_num' => $post['tuihuo_num'], 'cur_stock' => $stock['stock'], 'addtime' => time(), 'remark' => db('order')->find($order_detail['order_id'])['order_sn'], 'goods_spec_id' => $stock['goods_spec_id'], 'title' => $stock['spec_title'], 'order_id' => $order_detail['order_id']]);

            $order_detail_all = db('order_details')->where('order_id', $order_detail['order_id'])->select();

            $tuihuo_order = 1;//全部退货
            foreach ($order_detail_all as $v)
                if ($v['tuihuo_sign'] == 0 || $v['tuihuo_sign'] == 2)
                    $tuihuo_order = 2;//部分退货

            $order = db('order')->where('id', $order_detail['order_id'])->find();

            //积分规则
            $sys_point = db('sys_point')->where('id',2)->find();
            $point_rate = $sys_point['point']/10;
            $sys_point2 = db('sys_point')->where('id',6)->find();
            $point_rate2 = $sys_point2['point']/10;

            $cur_point = ceil(($order['final_amount'] - $order['tuihuo_amount'] - $cancel_amount) * $point_rate);//剩余积分
            $point = $order['score'] - $cur_point;
            $point2 = $point * $point_rate2 / $point_rate;

            $order_u = db('order')->update(['id' => $order_detail['order_id'], 'tuihuo_sign' => $tuihuo_order, 'score' => $cur_point]);
            $ordertuihuo = db('order')->where('id', $order_detail['order_id'])->setInc('tuihuo_amount', $cancel_amount);

            $point_r = 1;//积分操作状态
            $user_money_r = 1;//退余额

            if ($order_detail['uid'] > 0) {
                $member = db('user')->where('uid', $order_detail['uid'])->find();

                //退余额
                if ($order['pay_type'] == 3) {
                    $user_money = db('user')->where('uid', $order_detail['uid'])->setInc('user_money', $cancel_amount);
                    $money_log = db('user_wallet_log')->insert([
                        'uid' => $order_detail['uid'],
                        'admin_id' => $user['id'],
                        'store_id' => $user['store_id'],
                        'order_id' => $order['id'],
                        'amount' => $cancel_amount,
                        'cur_amount' => $member['user_money'] + $cancel_amount,
                        'chargetype' => 3,
                        'addtime' => time()
                    ]);
                    if ($user_money === false || $money_log === false)
                        $user_money_r = 0;
                }

                //退积分
                $pay_points = db('user')->where('uid', $order_detail['uid'])->setDec('pay_points', $point);//权益积分
                $level_point = db('user')->where('uid', $order_detail['uid'])->setDec('level_point', $point);//等级积分

                //积分日志
                $point_log = db('user_point_log')->insert([
                    'uid' => $order_detail['uid'],
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'order_id' => $order_detail['order_id'],
                    'uidtype' => 1,
                    'type' => 2,
                    'point' => -$point,
                    'curpoint' => $member['pay_points'] - $point,
                    'remark' => '退货',
                    'addtime' => time(),
                    'tuijianrenuid' => $member['pid']
                ]);

                $p = 1;
                if (db('user_point_log')->where('order_id', $order_detail['order_id'])->where('uid', $member['pid'])->find()) {
                    //推荐人
                    $pm = db('user')->where('uid', $member['pid'])->find();
                    //积分日志
                    $point_log2 = db('user_point_log')->insert([
                        'uid' => $member['pid'],
                        'admin_id' => session('user')['id'],
                        'store_id' => session('user')['store_id'],
                        'order_id' => $order_detail['order_id'],
                        'uidtype' => 3,
                        'type' => 2,
                        'point' => -$point2,
                        'curpoint' => $pm['pay_points'] - $point2,
                        'remark' => '退货',
                        'addtime' => time(),
                    ]);
                    $pay_points_p = db('user')->where('uid', $member['pid'])->setDec('pay_points', $point2);//权益积分
                    $level_point_p = db('user')->where('uid', $member['pid'])->setDec('level_point', $point2);//等级积分

                    if ($point_log2 === false || $pay_points_p === false || $level_point_p === false)
                        $p = 0;
                }

                if ($pay_points === false || $level_point === false || $point_log === false || $p === 0)
                    $point_r = 0;//积分失败
            }
            if ($order_u !== false && $order_action !== false && $order_details !== false && $log !== false && $ordertuihuo !== false && $point_r === 1 && $user_money_r === 1)
                $this->success('退货成功', '');
            else
                $this->error('退货失败');
        } else {
            $db = db('order_details')->where('id', $id)->find();
            $this->assign('list', $db);
            return $this->_form('order_details', 'cancel');
        }
    }

    public function findGoods()
    {
        $store_id = session('user')['store_id'];

        $post = input('post.');

        if (!isset($post['id'])) {
            $post['keywords'];
            $db = db('view_store_goods')->where('store_id', $store_id)->where('name|good_number', 'like', '%' . $post['keywords'] . '%')->select();
            return json(['data' => $db]);
        } else {
            $db = db('view_store_goods')->where('id', $post['id'])->find();
            $store = db('store')->find($store_id);
            if ($store['price_status'] == 1 && $db['trim_price'] > 0) {
                $begin = strtotime(date('H:i:s', $store['begin']));
                $end = strtotime(date('H:i:s', $store['end']));
                if (time() > $begin && time() < $end)
                    $db['price'] = $db['trim_price'];
            }
            return json(['data' => $db]);
        }
    }

}